// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
import fs from 'fs'
import path from 'path'

class UploadController extends BasicController {
    /**
     * 执行文件上传
     * @return {[type]} [description]
     */
    async actionIndex() {
        const limit = ['bmp','jpg','jpeg','png','gif','pdf'];
        // 上传单个文件
        const file = $_FILES['file'];
        if (file) {
            const { v4 } = require('uuid');
            const type = file.type.split('/')[0];
            const time = date('Ymd');
            const name = v4();
            const suffix = file.name.split('.')[1].toLowerCase();
            if (limit.indexOf(suffix) < 0) {
                throw new Error('错误类型');
            }
            // 创建可读流
            const reader = await fs.createReadStream(file.path);
            let url = "/upload/" + time
            let fileName = `/${name}.${suffix}`
            let filePath = ROOT_DIR + "/public" + url;
            if (!fs.existsSync(filePath)) {
                fs.mkdirSync(filePath);
            }
            const upStream = await fs.createWriteStream(filePath + fileName);
            if (reader.pipe(upStream)) {
                return url + fileName;
            } else {
                throw new Error('上传失败');
            }
        } else {
            throw new Error('请上传文件');
        }

    }

}

export default UploadController;